package com.youle.youleservice.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youle.youleservice.activity.ForbiddenActivity;
import com.youle.youleservice.bean.City;
import com.youle.youleservice.bean.Location;
import com.youle.youleservice.bean.Province;
import com.youle.youleservice.constance.Config;
import com.youle.youleservice.constance.Constans;
import com.youle.youleservice.greedao.CityDao;
import com.youle.youleservice.greedao.DBHelper;
import com.youle.youleservice.greedao.ProvinceDao;
import com.youle.youleservice.http.Data;
import com.youle.youleservice.http.Req;
import com.youle.youleservice.http.Rsp;
import com.youle.youleservice.http.TerminalStatue;
import com.youle.youleservice.listener.HttpCallback;
import com.youle.youleservice.listener.MyLocationListener;
import com.youle.youleservice.manager.BDLocationManager;
import com.youle.youleservice.manager.OkhttpManager;
import com.youle.youleservice.util.AESUtil;
import com.youle.youleservice.util.DeviceUtil;
import com.youle.youleservice.util.PrefrenceUtil;
import com.youle.youleservice.util.TimeUtil;

import java.util.List;

/**
 * Created by Administrator on 2018/8/8.
 */

public class CoreService extends Service {

    BDLocationManager mLocationManager;
    List<Province> mProvinces;
    List<City> mCities;
    String mLastLocationString;

    @Override
    public void onCreate() {
        super.onCreate();
        registerTimerFilter();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mLocationManager == null) {
            synchronized (CoreService.class) {
                if (mLocationManager == null) {
                    mLocationManager = new BDLocationManager();
                    mLocationManager.init(this, myLocationListener);
                    mLocationManager.start();
                }
            }
        }
        initProvinces();
        initCities();
        if (PrefrenceUtil.isForbiddent(this)) {
            startForbiddenActivity();
        } else {

        }
        return Service.START_STICKY;
    }

    MyLocationListener myLocationListener = new MyLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            super.onReceiveLocation(location);

            //获取定位结果
            StringBuffer sb = new StringBuffer(256);

            sb.append("time : ");
            sb.append(location.getTime());    //获取定位时间

            sb.append("\nerror code : ");
            sb.append(location.getLocType());    //获取类型类型

            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());    //获取纬度信息

            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());    //获取经度信息

            sb.append("\nradius : ");
            sb.append(location.getRadius());    //获取定位精准度

            if (location.getLocType() == BDLocation.TypeGpsLocation) {

                // GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());    // 单位：公里每小时   km/h

                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());    //获取卫星数

                sb.append("\nheight : ");
                sb.append(location.getAltitude());    //获取海拔高度信息，单位米

                sb.append("\ndirection : ");
                sb.append(location.getDirection());    //获取方向信息，单位度

                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息

                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                // 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息

                sb.append("\noperationers : ");
                sb.append(location.getOperators());    //获取运营商信息

                sb.append("\ndescribe : ");
                sb.append("网络定位成功");

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                // 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");

            } else if (location.getLocType() == BDLocation.TypeServerError) {

                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");

            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");

            }

            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());    //位置语义化信息

            List<Poi> list = location.getPoiList();    // POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }

            boolean isUpload = true;
            if (!assertProvincesNotEmpty()) {
                initProvinces();
                isUpload = false;
            }
            if (!assertCitiesNotEmpty()) {
                initCities();
                isUpload = false;
            }

            if (isUpload) {

                long pId = -1;
                String pName = "";
                String bdPronvince = location.getProvince();
                if (!TextUtils.isEmpty(bdPronvince)) {
                    for (Province p : mProvinces) {
                        if (bdPronvince.contains(p.getName())) {
                            pId = p.getId();
                            pName = p.getName();
                            break;
                        }
                    }
                }

                long cId = -1;
                String cName = "";
                String bdCity = location.getCity();
                if (!TextUtils.isEmpty(bdCity)) {
                    for (City c : mCities) {
                        if (bdCity.contains(c.getName())) {
                            cId = c.getId();
                            cName = c.getName();
                            break;
                        }
                    }
                }

                LogUtils.i("BaiduLocation:" + sb.toString());
                if (cId == -1 && pId == -1) {
                    LogUtils.e("定位失败");
                    return;
                }
                String imei = DeviceUtil.getImei(CoreService.this);
                Location upload = new Location();
                upload.setImei(imei);
                upload.setCreateTime(TimeUtil.fmtNow());
                upload.setTypeId(1L);
                upload.setLocationTime(location.getTime());
                upload.setTypeName("航镜");//?
                upload.setDeviceCode(imei);//?
                upload.setDeviceName(TextUtils.isEmpty(DeviceUtil.getImei(CoreService.this)) ? "0" : DeviceUtil.getImei(CoreService.this));//?
                upload.setProvinceId(Integer.parseInt(pId + ""));
                upload.setProvinceName(pName);
                upload.setCityId(Integer.parseInt(cId + ""));
                upload.setCityName(cName);
                String poiStr = "";
                List<Poi> pois = location.getPoiList();    // POI数据
                if (pois != null) {
                    for (Poi p : pois) {
                        poiStr += poiStr + p.getName() + "|";
                    }
                }
                upload.setDetailLocation(location.getAddrStr());
                upload.setLat(location.getLatitude());
                upload.setLng(location.getLongitude());

                Gson gson = new Gson();
                String jsonStr = gson.toJson(upload).toString();
                LogUtils.i("请求:" + jsonStr);
                String aesStr = AESUtil.encrypt(jsonStr);

                Req req = new Req();
                req.params = aesStr;
                jsonStr = gson.toJson(req).toString();
                mLastLocationString = jsonStr;
                LogUtils.i("请求:" + jsonStr);
            }

        }

    };

    BroadcastReceiver mTimerReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                String timeStr = TimeUtil.fmtNow("HH:mm");
                LogUtils.d("timeStr:" + timeStr);
                if (TextUtils.isEmpty(timeStr)) return;
                String[] split = timeStr.split(":");
                if (split != null && split.length > 1) {
                    String minStr = split[1];
                    if (minStr.equals("00")) {
                        if (TextUtils.isEmpty(mLastLocationString)) return;
                        OkhttpManager.post(mLastLocationString, new HttpCallback() {
                            @Override
                            public void succese(String content) {
                                LogUtils.i("succese=" + content);
                                Gson gson = new Gson();
                                Rsp rsp = gson.fromJson(content, Rsp.class);
                                Data data = rsp.data;
                                if (data != null && !TextUtils.isEmpty(data.t)) {
                                    String status = AESUtil.decrypt(data.t);
                                    LogUtils.i("data t=" + status);
                                    if (!TextUtils.isEmpty(status)) {
                                        TerminalStatue terminal = gson.fromJson(status, TerminalStatue.class);
                                        LogUtils.i("ternimal->" + terminal);
                                        if (terminal.getStatus().equals("1")) {//qiyong
                                            isForbidden = false;
                                            PrefrenceUtil.setForbiddent(CoreService.this, false);
                                            if (Constans.mForbiddenActivity != null) {
                                                if (!Constans.mForbiddenActivity.isFinishing()) {
                                                    Constans.mForbiddenActivity.finish();
                                                }
                                            }
                                        } else {
                                            PrefrenceUtil.setForbiddent(CoreService.this, true);
                                            isForbidden = true;
                                            startForbiddenActivity();
                                        }
                                    }
                                } else {
                                    LogUtils.e("data!=null&&!TextUtils.isEmpty(data.t)");
                                }
                            }


                            @Override
                            public void failure(int errcode, String error) {
                                LogUtils.i("failure=" + error);
                            }
                        });
                    }


                }
            }
        }
    };

    private boolean isForbidden = false;

    private boolean assertProvincesNotEmpty() {
        if (mProvinces != null && !mProvinces.isEmpty())
            return true;
        return false;
    }

    private boolean assertCitiesNotEmpty() {
        if (mCities != null && !mCities.isEmpty())
            return true;
        return false;
    }

    private void initProvinces() {
        final ProvinceDao provinceDao = DBHelper.getProvinceDao(this);
        if (provinceDao != null) {
            mProvinces = provinceDao.loadAll();
            if (mProvinces == null || mProvinces.isEmpty()) {
                OkhttpManager.post(Config.HTTP_URL_PROVINCE_LIST, "", new HttpCallback() {
                    @Override
                    public void succese(String content) {
                        Gson gson = new Gson();
                        mProvinces = gson.fromJson(content, new TypeToken<List<Province>>() {
                        }.getType());
                        if (mProvinces != null && !mProvinces.isEmpty()) {
                            try {
                                provinceDao.insertInTx(mProvinces);
                            } catch (Exception e) {
                                LogUtils.d("content=" + content);
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void failure(int errcode, String error) {
                    }
                });
            }
        }
    }

    private void initCities() {
        final CityDao cityDao = DBHelper.getCityDao(this);
        if (cityDao != null) {
            mCities = cityDao.loadAll();
            if (mCities == null || mCities.isEmpty()) {
                OkhttpManager.post(Config.HTTP_URL_CITY_LIST, "", new HttpCallback() {
                    @Override
                    public void succese(String content) {
                        Gson gson = new Gson();
                        mCities = gson.fromJson(content, new TypeToken<List<City>>() {
                        }.getType());
                        try {
                            cityDao.insertInTx(mCities);
                        } catch (Exception e) {
                            LogUtils.d("citys content=" + content);
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failure(int errcode, String error) {
                    }
                });
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationManager != null) {
            mLocationManager.stop();
        }
        unRegisterTimerFilter();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void startService(Context context) {
        Intent i = new Intent(context, CoreService.class);
        context.startService(i);
    }

    private void registerTimerFilter() {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Intent.ACTION_TIME_CHANGED);
            registerReceiver(mTimerReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void unRegisterTimerFilter() {
        try {
            unregisterReceiver(mTimerReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startForbiddenActivity() {
        Intent intent = new Intent(this, ForbiddenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

}
